import 'dart:ui';

import 'package:cbec_app/components/base/base_function.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class TextTagList extends StatefulWidget {
  ///选择属性
  final Function(String skuId)? onPropsClick;

  ///选择规格
  final Function(int index)? onSpecClick;

  ///选择拼团
  final Function(int index)? onGroupClick;

  ///属性列表
  final List propsList;

  ///sku列表
  final List skuList;

  ///规格列表
  final List specList;

  ///拼团列表
  final List? groupList;

  ///已选规格id
  final String specIds;

  ///选中的规格单位索引
  final int? selectedIndex;

  ///规格单位
  final String unit;

  ///是否显示拼团
  final bool isShowGroup;

  ///选中的拼团索引
  final int? selectedGroupIndex;

  ///文本类标签
  const TextTagList({super.key, required this.propsList, required this.skuList, required this.specList, required this.specIds, required this.unit, this.selectedIndex = 0, this.onPropsClick, this.onSpecClick, this.onGroupClick, this.groupList, this.isShowGroup = false, this.selectedGroupIndex = 0});

  @override
  State<StatefulWidget> createState() {
    return _TextTagStateList();
  }
}

class _TextTagStateList extends State<TextTagList> {
  List renderList = [];
  String selectedIds = ''; //已选规格id列表
  String curId = ''; //当前操作的id
  int curIndex = 0;
  @override
  void initState() {
    super.initState();
    curIndex = widget.selectedIndex!;
    selectedIds = widget.specIds;
    curId = selectedIds.split(';')[0];
    renderList = createRenderList();
  }

  @override
  Widget build(BuildContext context) {
    return Scrollbar(
        thickness: 0,
        child: SingleChildScrollView(
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: createSkuList()),
        ));
  }

  ///生成渲染列表
  List createRenderList() {
    List arr = [];
    List<String> brr = createAllPropsList();
    print('widget.propsList ===== ${widget.propsList}');
    for (int i = 0; i < widget.propsList.length; i++) {
      Map<String, dynamic> item = widget.propsList[i];
      for (var child in item['specValues']) {
        //设置选中
        if (selectedIds.contains(child['vid'])) {
          child['isActive'] = true;
        } else {
          child['isActive'] = false;
        }
        //设置禁用
        print('brr === $brr');
        print(' xxxxxx isInSkus ${isInSkus(item['pid'], child['vid'], brr)}  : ${item['pid']}  : ${child['vid']} : $brr');

        if (isInSkus(item['pid'], child['vid'], brr)) {
          child['isDisable'] = false;
        } else {
          child['isDisable'] = true;
        }
      }
      arr.add(item);
    }
    return arr;
  }

  ///获取当前选中属性所有可能的属性组合
  List<String> getCurPropsCombineList(List<String> arr) {
    List<String> brr = [];
    // print(' selectedIds   ===== $selectedIds');
    List<String> idList = selectedIds.split(';');
    // 855536676250939565:855536992711180490
    for (var item in arr) {
      for (var id in idList) {
        if (item.contains(id)) {
          brr.add(item);
        }
      }
    }
    return brr;
  }

  ///获取当前属性是否存在于sku属性列表
  bool isInSkus(String pid, String vid, List<String> list) {
    bool isIn = false;
    List<String> arr = getCurPropsCombineList(list);
    String id = '$pid:$vid';
    for (var item in widget.skuList) {
      for (var prop in list) {
        if (prop.contains(id) && (item['propPath'] as String).contains(prop)) {
          isIn = true;
          break;
        }
      }
    }
    return isIn;
  }

  ///获取属性id列表
  List getPropsIdsList() {
    List brr = [];
    print('propsList ===== $widget.propsList');
    for (int i = 0; i < widget.propsList.length; i++) {
      Map<String, dynamic> item = widget.propsList[i];
      brr.add([]);
      for (var child in item['specValues']) {
        String group = '${item['pid']}:${child['vid']}';
        brr[i].add(group);
      }
    }

    print('getPropsIdsList ==== $brr');

    return brr;
  }

  ///获取所有属性所有组合列表
  List getAllCombineList() {
    List arr = getPropsIdsList();
    if (arr.isEmpty) {
      return [];
    }
    List brr = doExchange(arr);

    print('brr ======= $brr');

    if (brr.isEmpty) {
      return [];
    }

    List crr = [];
    if (brr[0] is List) {
      //二维数组
      return brr;
    } else {
      //一维数组
      for (var item in brr) {
        crr.add([item]);
      }
      return crr;
    }
  }

  ///属性组合
  doExchange(arr) {
    var len = arr.length;
    // 当数组大于等于2个的时候
    if (len >= 2) {
      // 第一个数组的长度
      var len1 = arr[0].length;
      // 第二个数组的长度
      var len2 = arr[1].length;
      // 2个数组产生的组合数
      var lenBoth = len1 * len2;
      //  申明一个新数组,做数据暂存
      var items = List<dynamic>.filled(lenBoth, '');
      // 申明新数组的索引
      var index = 0;
      // 2层嵌套循环,将组合放到新数组中
      for (var i = 0; i < len1; i++) {
        for (var j = 0; j < len2; j++) {
          if (arr[0][i] is List) {
            List<dynamic> _list = [];
            _list.addAll(arr[0][i]);
            _list.addAll([arr[1][j]]);
            items[index] = _list;
          } else {
            List<dynamic> _list = [];
            _list.addAll([arr[0][i]]);
            _list.addAll([arr[1][j]]);
            items[index] = _list;
          }
          // items[index] = arr[0][i] + arr[1][j];
          index++;
        }
      }
      // 将新组合的数组并到原数组中
      // var newArr = new Array(len -1);
      var newArr = List<dynamic>.filled(len - 1, []);
      for (var i = 2; i < arr.length; i++) {
        newArr[i - 1] = arr[i];
      }
      newArr[0] = items;
      // newArr[0] = items;
      // 执行回调
      return doExchange(newArr);
    } else {
      return arr[0];
    }
  }

  ///生成所有属性的拼接组合
  List<String> createAllPropsList() {
    List arr = getAllCombineList();
    List<String> crr = [];
    for (var item in arr) {
      String str = (item as List).join(';');
      crr.add(str);
    }
    return crr;
  }

  ///设置选中
  void setSelected(String pid, String vid) {
    curId = '$pid:$vid';
    List<String> arr = selectedIds.split(';');
    List<String> brr = [];
    for (var item in arr) {
      if (item.contains(pid)) {
        brr.add(curId);
      } else {
        brr.add(item);
      }
    }
    selectedIds = brr.join(';');
    renderList = createRenderList();
  }

  ///生成规格列表
  List<Widget> createSkuList() {
    List<Widget> arr = [];
    for (var item in renderList) {
      arr.add(Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(top: 20.h, bottom: 12.h),
            child: Text(
              item['specName'],
              style: setTextStyle(13, FontWeight.w400, ThemeConfig.mainTextColor),
            ),
          ),
          Wrap(runSpacing: 19, spacing: 19, children: List.generate(item['specValues'].length, (index) => textTag(item['pid'], item['specValues'][index])))
        ],
      ));
    }

    ///生成规格
    arr.add(Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          margin: EdgeInsets.only(top: 20.h, bottom: 12.h),
          child: Text(
            '规格',
            style: setTextStyle(13, FontWeight.w400, ThemeConfig.mainTextColor),
          ),
        ),
        Wrap(runSpacing: 19, spacing: 19, children: List.generate(widget.specList.length, (index) => specTag(index)))
      ],
    ));

    ///生成拼团
    if (widget.isShowGroup) {
      arr.add(Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(top: 20.h, bottom: 12.h),
            child: Text(
              '拼团人数',
              style: setTextStyle(13, FontWeight.w400, ThemeConfig.mainTextColor),
            ),
          ),
          Wrap(runSpacing: 19, spacing: 19, children: List.generate(widget.groupList!.length, (index) => groupTag(index)))
        ],
      ));
    }
    return arr;
  }

  ///规格标签
  Widget specTag(int index) {
    return BaseInteractive(
        childWidget: Container(
          padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 5.h, bottom: 5.h),
          decoration: index == curIndex ? activeDecoration() : defaultDecoration(),
          child: Text(
            '${widget.specList[index]['specNum']}${widget.unit}',
            style: setTextStyle(13, FontWeight.w300, ThemeConfig.mainTextColor),
          ),
        ),
        onClick: () {
          setState(() {
            curIndex = index;
          });
          if (widget.onSpecClick != null) {
            widget.onSpecClick!(index);
          }
        });
  }

  ///拼团标签
  Widget groupTag(int index) {
    return BaseInteractive(
        childWidget: Container(
          padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 5.h, bottom: 5.h),
          decoration: index == curIndex ? activeDecoration() : defaultDecoration(),
          child: Text(
            '${widget.groupList![index]['peopleNumber']}人团',
            style: setTextStyle(13, FontWeight.w300, ThemeConfig.mainTextColor),
          ),
        ),
        onClick: () {
          setState(() {
            curIndex = index;
          });
          if (widget.onGroupClick != null) {
            widget.onGroupClick!(index);
          }
        });
  }

  ///文本标签
  Widget textTag(String pid, Map<String, dynamic> item) {
    return BaseInteractive(
        childWidget: Container(
          padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 5.h, bottom: 5.h),
          decoration: item['isActive'] ? activeDecoration() : (item['isDisable'] ? disableDecoration() : defaultDecoration()),
          child: Text(
            item['valueName'],
            style: setTextStyle(13, FontWeight.w300, ThemeConfig.mainTextColor),
          ),
        ),
        onClick: () {
          if (item['isDisable']) {
            return;
          }
          setState(() {
            print('pid ==== $pid');
            setSelected(pid, item['vid']);
          });
          if (widget.onPropsClick != null && getSkuId() != '') {
            widget.onPropsClick!(getSkuId());
          }
        });
  }

  ///获取选中的skuId
  String getSkuId() {
    String skuId = '';
    print('getSkuId onSelectSku === ${widget.skuList}');
    for (var item in widget.skuList) {
      if ((item['propPath'] as String).contains(selectedIds)) {
        skuId = item['skuId'];
      }
    }
    print('getSkuId onSelectSku === $skuId');
    return skuId;
  }

  ///默认样式
  BoxDecoration defaultDecoration() {
    return BoxDecoration(color: const Color(0xfff9f9f9), border: Border.all(color: Colors.transparent), borderRadius: const BorderRadius.all(Radius.circular(25)));
  }

  ///激活样式
  BoxDecoration activeDecoration() {
    return BoxDecoration(color: const Color(0xffF7D8D5), border: Border.all(color: ThemeConfig.themeColor), borderRadius: const BorderRadius.all(Radius.circular(25)));
  }

  ///禁用样式
  BoxDecoration disableDecoration() {
    return BoxDecoration(color: Colors.grey, border: Border.all(color: Colors.transparent), borderRadius: const BorderRadius.all(Radius.circular(25)));
  }
}
